<?php

namespace Frieza\Modules\LightTopic\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\service\Photos;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Doraemon\service\Elasticsearch\Photo as esPhotoService;
use Encore\Admin\Layout\Row;
use Illuminate\Http\Request;

class LightTopicContentController extends Controller
{
    public function index(Content $content, Request $request)
    {
        $params = $request->all();

        $where = [];

        if (!isset($params['per_page'])) {
            $params['per_page'] = 20;
        }

        if (!isset($params['page'])) {
            $params['page'] = 1;
        } else {
            // es默认查询到10000条数据
            $totalPage = ceil(10000 / $params['per_page']);
            if ($params['page'] > $totalPage) $params['page'] = $totalPage;
        }

        if (isset($params['light_topic']) && !empty($params['light_topic'])) {
            $where['AND']['light_topic'] = strtolower($params['light_topic']);
        } else {
            $where['AND']['light_topic[!]'] = '';
        }

        if (isset($params['note_id']) && !empty($params['note_id'])) {
            $where['AND']['id'] = $params['note_id'];
        }

        if (isset($params['uid']) && !empty($params['uid'])) {
            $where['AND']['uid'] = $params['uid'];
        }

        if (isset($params['addtime']) && !empty($params['addtime'])) {
            if ($params['addtime']['start']) $where['AND']['addtime[>=]'] = strtotime($params['addtime']['start']);
            if ($params['addtime']['end']) $where['AND']['addtime[<=]'] = strtotime($params['addtime']['end']);
        }

        $where['LIMIT'] = [
            ($params['page'] - 1) * $params['per_page'],
            $params['per_page']
        ];

        $where['ORDER']['addtime'] = 'DESC';

        if (isset($where['AND']['light_topic[!]']) && $where['AND']['light_topic[!]'] == '') {
            $lightTopicPhotos = (new esPhotoService)->getLightTopicPhotos($where, false);
        } else {
            $lightTopicPhotos = (new esPhotoService)->getLightTopicPhotos($where);
        }

        $photosId = $lightTopicPhotos['note_ids'];
        $lightTopic = $lightTopicPhotos['light_topic'];
        $isTop = $lightTopicPhotos['is_top'];
        $total = $lightTopicPhotos['total'];

        $photos = Photos::getMultiPhotoInfos($photosId, null);
        $gridModel = new pGridDataModel($this->formatPhoto($photos, $lightTopic, $isTop), $total, [
            'perPage' => $params['per_page']
        ]);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            //$grid->disableActions();

            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->expand();
                $filter->column(1 / 3, function ($filter) {
                    $filter->dropDown('search_id', [
                        'note_id' => 'Note id',
                        'uid' => '用户uid',
                    ]);
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->equal('light_topic', '轻话题标题');
                });
                $filter->column(1 / 3, function ($filter) {
                    $filter->between('addtime', '创建时间')->datetime();
                });
            });

            $grid->column('photo_id', '内容ID')->expand(function () {
                return $this->expand;
            }, true)->width(150);
//            $grid->column('light_topic', '回答关联轻话题');
            $grid->column('remark', '回答内容')->width(750)->display(function () {
                return "<strong>[photo_id]:</strong>{$this->photo_id}<br><strong>[标题]:</strong>{$this->title}<br><strong>[正文]:</strong>{$this->remark}";
            });
            $grid->column('addtime', '发布时间')->width(150);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('counter', '交互情况')->width(100)->display(function () {
                return "赞：{$this->counter['like']} <br/> 评论：{$this->counter['comments']}  <br/> 收藏：{$this->counter['favorite']}  <br/> 分享：{$this->counter['share']} ";
            });

            Admin::script($this->setScript());
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableEdit();
                $actions->disableView();

                $isTop = 2;
                $isBottom = 0;
                $cancel = 1;
                switch ($actions->row->is_top) {
                    case 0:
                        $top = '';
                        $bottom = '取消置底';
                        break;
                    case 1:
                        $top = '置顶';
                        $bottom = '置底';
                        break;
                    case 2:
                        $top = '取消置顶';
                        $bottom = '';
                        break;
                }

                if (!empty($top) && !empty($bottom)) {
                    $actions->prepend('<p><a class="setTop label  label-info" data-id="' . $actions->row->photo_id . '"  data-best="' . $isBottom . '" data-circle_id="' . $actions->row->circle_id . '" href="javascript:void(0);">' . $bottom . '</a></p>');
                    $actions->prepend('<p><a class="setTop label  label-info" data-id="' . $actions->row->photo_id . '"  data-best="' . $isTop . '" data-circle_id="' . $actions->row->circle_id . '" href="javascript:void(0);">' . $top . '</a></p>');
                } elseif (!empty($top) && empty($bottom)) {
                    $actions->prepend('<p><a class="setTop label  label-info" data-id="' . $actions->row->photo_id . '"  data-best="' . $cancel . '" data-circle_id="' . $actions->row->circle_id . '" href="javascript:void(0);">' . $top . '</a></p>');
                } elseif (empty($top) && !empty($bottom)) {
                    $actions->prepend('<p><a class="setTop label  label-info" data-id="' . $actions->row->photo_id . '"  data-best="' . $cancel . '" data-circle_id="' . $actions->row->circle_id . '" href="javascript:void(0);">' . $bottom . '</a></p>');
                }

            });
        });

        return $content
            ->header('轻话题内容管理')
            ->breadcrumb(
                ['text' => '轻话题列表', 'url' => '/LightTopic/index'],
                ['text' => '轻话题内容列表', 'url' => '/LightTopic/answer/list']
            )
            ->body($listGrid);
    }

    private function formatPhoto($photos, $lightTopic, $isTop)
    {
        $res = [];
        $i = 0;
        foreach ($photos as $photo) {
            $picTmp = [];
            if ($photo['photo']['photo_info']['image_list']) {
                foreach ($photo['photo']['photo_info']['image_list'] as $p) {
                    $picTmp[] = [
                        'pic_url' => $p['pic_url'],
                        'pic_id' => $p['pic_id'],
                        'photo_id' => $photo['photo']['photo_info']['id'],
                        'is_video' => 0,
                    ];
                }
            } else {
                if ($photo['photo']['photo_info']['pic_url']) {
                    $picTmp[] = [
                        'pic_url' => $photo['photo']['photo_info']['pic_url'],
                        'pic_id' => $photo['photo']['photo_info']['pin_pic_id'],
                        'photo_id' => $photo['photo']['photo_info']['id'],
                        'is_video' => 0,
                    ];
                }
            }

            if ($photo['photo']['photo_info']['video_info']) {
                $picTmp[] = [
                    'pic_url' => $photo['photo']['photo_info']['video_info']['play_url_for_frieza'],
                    'pic_id' => $photo['photo']['photo_info']['video_info']['video_id'],
                    'photo_id' => $photo['photo']['photo_info']['id'],
                    'is_video' => 1,
                ];
                $picTmp[] = [
                    'pic_url' => $photo['photo']['photo_info']['video_info']['pic_url'],
                    'pic_id' => $photo['photo']['photo_info']['video_info']['cover_pic_id'],
                    'photo_id' => $photo['photo']['photo_info']['id'],
                    'is_video' => 0,
                ];
            }

            $res[] = [
                'id' => ++$i,
                'photo_id' => $photo['photo']['photo_info']['id'],
                'remark' => $this->highLight($photo['photo']['photo_info']['remark']),
                'title' => $photo['photo']['photo_info']['title'],
                'addtime' => date('Y-m-d H:i:s', $photo['photo']['photo_info']['addtime']),
                'uid' => $photo['photo']['user_info']['uid'],
                'user' => [
                    'uid' => $photo['photo']['user_info']['uid'],
                    'nick' => $photo['photo']['user_info']['nick'],
                    'type' => $photo['photo']['user_info']['type'],
                ],
                'counter' => $photo['photo']['counter'],
                'images' => $picTmp,
                'status' => $photo['photo']['photo_info']['status'],
                'is_best' => $photo['photo']['photo_info']['is_best'],
                'is_bottom' => $photo['photo']['photo_info']['is_bottom'],
                'is_fold' => $photo['photo']['photo_info']['is_fold'],
                'expand' => $this->getPicExpand(['pics' => $picTmp]) . $this->_getDivLine(),
                'topic_title' => $photo['photo']['photo_info']['topic']['title'],
                'light_topic' => $lightTopic[$photo['photo']['photo_info']['id']],
                'is_top' => $isTop[$photo['photo']['photo_info']['id']],
            ];
        }

        return $res;
    }

    public function setTopOrBottom(Request $request)
    {
        $params = $request->all();
        $noteId = $params['note_id'];
        $isTop = $params['is_top'];
        return (new esPhotoService)->setLightTopicTop($noteId, $isTop);
    }

    private function getPicExpand($picArr)
    {
        $row = new Row();
        if ($picArr['pics']) {
            $GirdModel = new pGridDataModel($picArr, null, ['pageName' => '']);
            $grid = new Grid($GirdModel);
            $grid->disablePagination();
            $grid->disableCreateButton();
            $grid->disableFilter();
            $grid->disableRowSelector();
            $grid->disableColumnSelector();
            $grid->disableTools();
            $grid->disableActions();
            $grid->disableExport();
            $grid->column('pic', 'pic信息')->display(function () {
                $infos = json_decode($this, true);
                if ($infos && is_array($infos)) {
                    $pic = '';
                    foreach ($infos as $picInfo) {
                        if ($picInfo['is_video']) {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<video src='" . $picInfo['pic_url'] . "' height='300px' controls /></video>" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        } else {
                            $pic .= "<div style='display:inline-block;margin:10px;height:220px;'>" .
                                "<img src='" . $picInfo['pic_url'] . "' height='200px' class='img' />" .
                                "<br>" . $picInfo['pic_id'] . "</div>";
                        }
                    }
                    return $pic;
                }
            });

            $grid->disablePagination();
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                $actions->disableEdit();
                $actions->disableDelete();
                $actions->disableView();
            });
            $row->column('12', $grid);
            return $row->render();
        }
        return '';
    }

    /**
     * 分割线
     * @return string
     */
    private function _getDivLine()
    {
        return "<div style='width:100%;height:5px;background-color:#4169E1;margin-bottom:20px;'></div>";
    }


    // 正文中轻话题高亮
    private function highLight($remark)
    {
        preg_match_all('/#([\w\-]{1,15}+)/u', $remark . ' ', $userTags);

        if (isset($userTags[0]) && !empty($userTags[0])) {
            $replaceRemarkArr = [];
            foreach ($userTags[0] as $userTag) {
                $replaceRemarkArr[] = '<b style="color:deepskyblue;">' . $userTag . '</b>';
            }
            return str_replace($userTags[0], $replaceRemarkArr, $remark);
        }

        return $remark;
    }

    /**
     * @return string
     */
    private
    function setScript()
    {
        return <<<SCRIPT
    $('.setTop').unbind('click').click(function(){
        var id= $(this).attr('data-id');
        var is_top = $(this).attr('data-best');
        let that = $(this)
        let url = '/admin/LightTopic/answer/isTop/';
        let params = {
            is_top:is_top,
            note_id:id,
        };
        $.post(url, params , function (result) {                
            if (result) {
                layer.msg('成功');                                
            } else {
                layer.msg('失败');
            }
            setTimeout(function () {
                parent.window.location.reload();
            }, 1000);
        });
    });
    SCRIPT;
    }
}
